package stud.mpgame.network;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import java.io.IOException;

class UserObjectDecoder extends CumulativeProtocolDecoder {

    private int protocolVersion;
    private long startAppTime;

    public UserObjectDecoder(long startAppTime, int protocolVersion) {
        this.protocolVersion = protocolVersion;
        this.startAppTime = startAppTime;
    }

    public boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
        if (ioBuffer.prefixedDataAvailable(4)) {
            ioBuffer.getInt(); //length
            long currentTime = System.currentTimeMillis();
            int receivedTime = (int) (currentTime - startAppTime);
            Message message = new Message(ioBuffer, ioSession, receivedTime);
            if(message.getProtocolVersion() == protocolVersion)
                protocolDecoderOutput.write(message);
            else
                throw new IOException("Wrong protocol version");
            return true;
        } else {
            return false;
        }
    }

    public void finishDecode(IoSession ioSession, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {

    }

    public void dispose(IoSession ioSession) throws Exception {

    }
}
